package com.weaver.seconddev.api.tl.gr_api;

/**
 * E9原始类路径:com.api.tl.gr_api.GrAttachmentPushAction
 * JAVA替换说明文档:https://ncnb71xwgeda.feishu.cn/wiki/JLsjwxK8xiHuPIkdu0Dc27Rlnaf?from=from_copylink
 */
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.weaver.common.hrm.util.HrmContextUtil;
import com.weaver.common.hrm.util.Util;
import com.weaver.eteams.file.client.file.FileData;
import com.weaver.eteams.file.client.file.FileObj;
import com.weaver.eteams.file.client.param.storage.info.FileStorageInfo;
import com.weaver.eteams.file.client.remote.FileClientService;
import com.weaver.file.ud.api.FileDownloadService;
import com.weaver.file.ud.rpc.storage.match.FileStoRuleMatchClient;
import com.weaver.file.ud.storage.match.StoRuleMatchDto;
import com.weaver.file.ud.storage.match.StoRuleMatchParam;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.seconddev.api.tl.request.AttachmentsReq;
import com.weaver.seconddev.api.tl.request.GetUploadFileInfoReq;
import com.weaver.seconddev.api.tl.response.UploadFileInfoRsp;
import com.weaver.seconddev.api.tl.service.SAPCommonService;
import lombok.Getter;
import lombok.Setter;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.verupgrade.conn.CONN_TYPE;
import java.lang.*;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
import com.weaver.verupgrade.workflow.request.RequestManager;
import com.weaver.esb.api.rpc.EsbServerlessRpcRemoteInterface;
import com.weaver.common.base.entity.result.WeaResult;
import org.springframework.beans.factory.annotation.Autowired;
import com.weaver.verupgrade.soa.workflow.request.RequestInfo;
import java.util.Map;
import java.util.HashMap;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.interfaces.workflow.action.Action;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * GR节点后事件-附件推送
 * @Author daifeifan
 * @date 2024/10/28 14:00
 */
@Service("tl_gr_api_GrAttachmentPushAction")
public class GrAttachmentPushAction implements Action, EsbServerlessRpcRemoteInterface {

    // 对应E9的请求信息对象
    @Autowired
    private RequestInfo requestInfoTemp;


    public static final Logger logger_996e17f1 = LoggerFactory.getLogger(GrAttachmentPushAction.class);

    //private final SAPCommonService sapCommonService = new SAPCommonService();

    @Resource(name = "tl_service_EcologyCommonService2")
    private EcologyCommonService2 ecologyCommonService2;


    @Resource(name = "tl_service_SAPCommonService")
    private SAPCommonService sapCommonService;
    @Getter
    @Setter
    public String // 流程主表名
            workflowTableName;

    @Getter
    @Setter
    public String // po字段名称
            poColumn;

    @Getter
    @Setter
    public String // 附件字段名称
            attachmentColumn;


    @Override
    public WeaResult<Map<String, Object>> execute(Map<String, Object> requestInfoMap) {
        Map<String, Object> weaverResultMap = new HashMap<>();
        Long requestIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("requestid", -1)));
        Long userIdTemp = Long.parseLong(String.valueOf(requestInfoMap.getOrDefault("userid", -1)));
        workflowTableName = String.valueOf(requestInfoMap.getOrDefault("workflowTableName", ""));
        poColumn = String.valueOf(requestInfoMap.getOrDefault("poColumn", ""));
        attachmentColumn = String.valueOf(requestInfoMap.getOrDefault("attachmentColumn", ""));
        RequestInfo requestInfo = requestInfoTemp.getRequestInfo(requestIdTemp, userIdTemp);
        String pushApprovedResult = SUCCESS;
        logger_996e17f1.info(String.valueOf(">>>>GrAttachmentPushAction begin execute param => workflowTableName=" + workflowTableName + ",poColumn=" + poColumn + ",attachmentColumn=" + attachmentColumn));
        RecordSet recordSet = I18nContextUtil.getBean(RecordSet.class);
        try {
            /* 获取requestId
 TODO 返回值:requestId 存在类型转换风险 e9类型:java.lang.String e9真实类型: int  e10类型:java.lang.String e10真实类型: long */
            String requestId = requestInfo.getRequestid();
            // 主表查询
            //String querySQL = "select\n" + "  m." + poColumn + " as poNumber,\n" + "  m." + attachmentColumn + " as attachmentId\n" + "from\n" + "  " + workflowTableName + " m\n" + "where\n" + "  requestId = '" + requestId + "'";
            String querySQL = "SELECT  m."+poColumn+" AS poNumber,"+ "  m." + attachmentColumn + " as attachmentId" +
                    " FROM (\n" +
                    "\tSELECT b.*, a.requestid\n" +
                    "\tFROM e10_core_business.wfc_form_data a, e10_core_business."+workflowTableName+" b\n" +
                    "\tWHERE a.dataid = b.form_data_id\n" +
                    "\t\tAND a.delete_type = 0\n" +
                    "\t\tAND a.tenant_key = 'tl2k2r96ty'\n" +
                    ") m\n" +
                    " WHERE m.requestid = '"+ requestId +"'" +
                    "\tAND m.delete_type = 0\n" +
                    "\tAND m.tenant_key = 'tl2k2r96ty'";
            logger_996e17f1.info(String.valueOf("querySQL=>" + querySQL));
            String poolname = CONN_TYPE.workflow.getType();
            // TODO E10执行sql方法第二参数必须指定源，默认使用流程源，单体客户无需修改，微服务/组合客户需根据查询表所属服务切换源，或使用外部数据源
            recordSet.executeQuery(querySQL, poolname);
            String errorMsg = "";
            if (recordSet.next()) {
                String poNumber = recordSet.getString("poNumber");
                String attachmentId = recordSet.getString("attachmentId");
                if (StringUtils.isBlank(attachmentId)) {
                    logger_996e17f1.info(String.valueOf("CreatePurchaseCommon.uploadAttachments attachmentId is null skip push！"));
                    errorMsg = "success";
                } else {
                    errorMsg = sapCommonService.uploadAttachments(requestId, poNumber, attachmentId);
                    logger_996e17f1.info(String.valueOf("CreatePurchaseCommon.uploadAttachments return errorMsg = " + errorMsg));
                }
            }
            if (!"success".equals(errorMsg)) {
                pushApprovedResult = FAILURE_AND_CONTINUE;
            }
        } catch (Exception e) {
            pushApprovedResult = FAILURE_AND_CONTINUE;
        }
        return WeaResult.success(getResultMapForAction(weaverResultMap, "result", pushApprovedResult, requestInfo.getRequestManager()));
    }

    Map<String, Object> getResultMapForAction(Map<String, Object> map, String key, Object value, RequestManager requestManager) {
        if (key != null && !key.isEmpty()) {
            map.put(key, value);
        }
        String msgContent = requestManager.getMessagecontent();
        if (msgContent != null && !msgContent.isEmpty()) {
            map.put("msgContent", msgContent);
        }
        String msgId = requestManager.getMessageid();
        if (msgId != null && !msgId.isEmpty()) {
            map.put("msgId", msgId);
        }
        return map;
    }



}
